#!/usr/bin/python

# -*- coding: utf-8 -*-
###############################################################################
#
#           Copyright (c) 2010 Miltuxon // mcmanzo@miltuxon.com.ar
#
#  Este programa es software libre; usted puede redistruirlo y/o modificarlo bajo
#  los terminos de la Licencia Publica General GNU, tal y como esta publicada
#  por la Free Software Foundation; ya sea la version 3 de la Licencia, o (a su
#  eleccion) cualquier version posterior.
#  
#  Este programa se distribuye con la intencion de ser util, pero SIN NINGUNA
#  GARANTIA; incluso sin la garantia implicita de USABILIDAD O UTILIDAD PARA UN
#  FIN PARTICULAR. Vea la Licencia Publica General GNU para mas detalles.
#  
#  Una copia de la Licencia Publica General GNU puede se descargada del sig sitio
#                    http://www.gnu.org/licenses/gpl.html
#
###############################################################################

#comando para rastrear las variables para gettext
#xgettext --language=Python --keyword=self._ --output=gbum.pot bumgtk.py

import gtk
import bitly
import gettext
import locale
import os
from urlparse import urlparse


LOGIN='miltuxon'
APIKEY='R_c13da9b834802cf618b8b0031a66d3b1'
APPTITLE='GTK+ Bit.ly URLs Manager'
APP_NAME = "gbum"

#clase para crear MessagesBox
class my_dialog(object):
	
	def destroyDialog(self, widget, data=None):
		self.dialog.destroy()
		
	
	def __init__(self,label, title, parent):
		
		self.dialog = gtk.Dialog(title=title, parent=parent, flags=gtk.DIALOG_MODAL, buttons=None)
		
		label = gtk.Label(label)
		label.set_use_markup(True)
		self.dialog.vbox.pack_start(label, True, True, 0)
		label.show()
				
		button = gtk.Button(None,gtk.STOCK_OK)
		button.connect("clicked", self.destroyDialog, None)
		self.dialog.action_area.pack_start(button, True, True, 0)
		button.show()
	
	def show(self):
		self.dialog.show()
	



class my_window(object):
	
	def my_clipboard(self, data):
		# get the clipboard
		clipboard = gtk.clipboard_get()	
		
		# set the clipboard text data
		clipboard.set_text(data)
		
		# make our data available to other applications
		clipboard.store()
		
		
	def check_clippboard(self, widget, data=None):
		clipboard = gtk.clipboard_get()	
		text = clipboard.wait_for_text()
		
		if text is not None: 
			url = urlparse(text)
			#si el protocolo es valido scheme contiene el protocolo
			if url.scheme != "":
				self.textbox.set_text(text) 
	
	
	def getURL(self, widget, data=None):
		URL = self.textbox.get_text()
		
		try:
			api=bitly.Api(login=LOGIN, apikey=APIKEY)
				
				
			if self.rbuttonS.get_active() == True:	
				urlPros=api.shorten(URL)
				dlg=my_dialog(self._("Shorten URL has been copied to clipboard"), self._("Info!"), self.window)

			if  self.rbuttonL.get_active() == True:
				urlPros=api.expand(URL)    
				dlg=my_dialog(self._("Expanded URL has been copied to clipboard"), self._("Info!"), self.window)
				

			self.my_clipboard(urlPros)
		
		except Exception, e:
			dlg=my_dialog(e, self._("Error!"), self.window)
			
		
		dlg.show()
		self.textbox.set_text('')
		
		
		
		
	def menuitem_response(self, widget, string):
		if string == 'M_About':
						
			string_about = "<span size='xx-large' weight='bold'>%s</span>\n" % APPTITLE
			string_about=string_about+"<span weight='bold'>"+self._("Version:")+"</span> 1.0.5.1b_20100928\n"
			string_about=string_about+"<span weight='bold'>"+self._("Author:")+"</span> Miltuxon - <span foreground='blue' underline='single'> http://www.miltuxon.com.ar</span>\n"
			string_about=string_about+"<span weight='bold'>"+self._("Thanks:")+"</span> Matias G. Ventura - <span foreground='blue' underline='single'>mgventura@miltuxon.com.ar</span>\n"
			string_about=string_about+"<span weight='bold'>"+self._("Bit.ly Api Library")+"</span> - <span foreground='blue' underline='single'>http://code.google.com/p/python-bitly/</span>" 
			
			dlg=dlg=my_dialog(string_about, self._("About"), self.window)
			dlg.show()
		elif string == 'M_Exit':
			self.destroy(widget, None)
		
		
	def destroy(self, widget, data=None):
		gtk.main_quit()
	
		
	
	
	def __init__(self):
		
		#### Esto es para las traducciones ####
		
		#self.local_path = os.path.abspath(os.path.dirname(sys.argv[0]))
		
		self.local_path = "/usr/share/locale/"

		# defino la lista de lenguajes
		langs = []
		#chequeo el lenguaje por defecto
		lc, encoding = locale.getdefaultlocale()
		if (lc):
			#si hay lenguaje por defecto es el primero de la lista
			langs = [lc]
			
		# Traigo los lenguajes soportados en el sistema
		language = os.environ.get('LANGUAGE', None)
		if (language):
			langs += language.split(":")
		"""Now add on to the back of the list the translations that we
		know that we have, our defaults"""
		langs += ["en_US", "es_AR"] #Aca defino los lenguajes a soportar
		
		"""Now langs is a list of all of the languages that we are going
		to try to use.  First we check the default, then what the system
		told us, and finally the 'known' list"""
		
		gettext.bindtextdomain(APP_NAME, self.local_path)
		gettext.textdomain(APP_NAME)
		# Get the language to use
		self.lang = gettext.translation(APP_NAME, self.local_path
			, languages=langs, fallback = True)
		"""Install the language, map self._() (which we marked our
		strings to translate with) to self.lang.gettext() which will
		translate them."""
		
		self._ = self.lang.gettext # self._ variable para gettext
		
		#################################################################
		
		self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
		self.window.set_border_width(0)
		self.window.set_title(APPTITLE)
		self.window.set_default_size(370, 120)
		self.window.set_icon_from_file('/usr/share/icons/bitly.xpm')
		
		self.window.connect("destroy", self.destroy)
		self.window.connect("focus_in_event", self.check_clippboard)
		
				
		#AGREGADO - MGV -  Matias G. Ventura 
		#module_dir_name = os.path.dirname(os.path.abspath(__file__))
		#icon_path = os.path.join(module_dir_name, 'bitly.ico')
		#self.window.set_icon_from_file(icon_path)
		
		#Contenedor principal Vertical
		box1 = gtk.VBox(False, 0)
		self.window.add(box1) #agrego el contenedor a la ventana
		
		##################### MENU ########################
		#inicializo el menu
		menu = gtk.Menu()

		# Items de menu
		menu_items = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
		img = gtk.image_new_from_stock(gtk.STOCK_ABOUT, gtk.ICON_SIZE_MENU)
		menu_items.set_image(img)
		
		menu.append(menu_items)
		
		menu_items.connect("activate", self.menuitem_response, 'M_About')
		menu_items.show()
	
		menu_items = gtk.ImageMenuItem(gtk.STOCK_QUIT)
		img = gtk.image_new_from_stock(gtk.STOCK_QUIT, gtk.ICON_SIZE_MENU)
		menu_items.set_image(img)
		
		menu.append(menu_items)
		
		menu_items.connect("activate", self.menuitem_response, 'M_Exit')
		menu_items.show()
		
		#menu raiz
		root_menu = gtk.MenuItem(self._("Menu"))
		root_menu.show()
		
		#El boton raiz del menu es un elemento del objeto menu
		root_menu.set_submenu(menu)
		
				
		#Genero la barra de menu y la posiciono en el contenedo
		menu_bar = gtk.MenuBar()
		box1.pack_start(menu_bar, True, True, 0)
		menu_bar.show()
		
		menu_bar.append (root_menu)
		#####################################################	
		
		#Label de la URL				
		label = gtk.Label(self._("Put URL here"))
		label.set_justify(gtk.JUSTIFY_LEFT)
		box1.pack_start(label, True, True, 0) #pongo el label en el contenedor principal
		label.show()
		
		#Textbox del la url
		self.textbox = gtk.Entry(max=255)
		self.textbox.set_max_length(255)
		box1.pack_start(self.textbox, True, True, 0) #pongo el text en el contenedor principal
		self.textbox.show()
		
		#creo el contenedor de los radiobuttons horizontal
		box2 = gtk.HBox(False, 0)
		box2.set_border_width(0)
		box1.pack_start(box2, True, True, 0) #agrego el contenedor de los radio al principal
				
		self.rbuttonS = gtk.RadioButton(None, self._("Shorten URL"))
		self.rbuttonS.set_active(True)
		box2.pack_start(self.rbuttonS, True, False, 0) #pongo el radio en el contenedor 2
		self.rbuttonS.show()

		self.rbuttonL = gtk.RadioButton(self.rbuttonS, self._("Expand Bit.ly URL"))
		box2.pack_start(self.rbuttonL, True, False, 0) #pongo el radio en el contenedor 2
		self.rbuttonL.show()
		
		box2.show() # Muestro el contenedor
		
		#separador
		separator = gtk.HSeparator()
		box1.pack_start(separator, False, False, 0) #Pongo el separador en el contenedor principal
		separator.show()
		
		button = gtk.Button(None,gtk.STOCK_EXECUTE)
		box1.pack_start(button, False, False, 0) #Pongo el boton en el contenedor principal
		button.connect("clicked", self.getURL, None)
		#button.connect_object("clicked", gtk.Widget.destroy,self.window)
		button.show()
		
		box1.show() #muestro el contenedor principal que ya  contiene todos los controles
	
		
		self.window.show()
		
		

	def main(self):
		gtk.main()
		
		


if __name__ == "__main__":
	ventana = my_window()
	ventana.main()

